<template>
  <div class="CityLocation">
    <van-index-bar :index-list="indexList">
      <!-- 定位 -->
      <van-index-anchor index="定位"
        ><span @click.stop="$emit('showcity', false)"
          >定位城市 （点击后退）</span
        >
      </van-index-anchor>
      <div class="van-cell location-city">
        <button>定位失败，请稍后重试</button>
      </div>

      <!-- 历史访问城市 -->
      <van-index-anchor index="最近"
        >最近访问的城市<span @click="delhistory()" class="delhistory"
          >清空</span
        ></van-index-anchor
      >
      <div class="van-cell recently-city">
        <ul class="recently">
          <li
            v-for="city in historyList"
            :key="city.nm"
            @click="
              $emit('city', city);
              $emit('showcity', false);
              setHistroy(city);
            "
          >
            {{ city.nm }}
          </li>
        </ul>
      </div>

      <!-- 热门 -->
      <van-index-anchor index="热门">热门城市</van-index-anchor>

      <div class="van-cell hot-city">
        <ul class="list">
          <li
            v-for="city in hotList"
            :key="city.id"
            @click="
              setHistroy(city);
              $emit('city', city);
              $emit('showcity', false);
            "
          >
            {{ city.nm }}
          </li>
        </ul>
      </div>

      <!-- A-Z -->
      <div class="A-Z" v-for="citys in cities" :key="citys.str">
        <van-index-anchor :index="citys.str">{{ citys.str }}</van-index-anchor>
        <ul>
          <li
            class="city-list"
            v-for="city in citys.arr"
            :key="city.id"
            @click="
              setHistroy(city);
              $emit('city', city);
              $emit('showcity', false);
            "
          >
            {{ city.nm }}
          </li>
        </ul>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  data() {
    return {
      // 自定义索引
      indexList: ["定位", "最近", "热门"],
      hotList: [], // 热门城市
      reHot: [], // 用来过滤
      cities: [], // 城市列表
      historyList: [],
    };
  },
  methods: {
    // 添加历史记录
    setHistroy(city) {
      if (city) {
        // 获取本地存储记录
        let historys = localStorage.getItem("history");
        let historyArr = [];
        if (historys) {
          historyArr = JSON.parse(historys); //还原localStorage数据
        }
        // 添加到最前面
        historyArr.unshift(city);
        // 去重
        // console.log(historyArr, "去重");
        // historyArr = _.uniq(historyArr);

        /* for (let i = 0; i < historyArr.length - 1; i++) {
          // console.log(city.id, historyArr[i].id);
          for (let j = i + 1; j < historyArr.length - 1; j++) {
            if (historyArr[i].id == historyArr[j].id) {
              historyArr.splice(i, 1);
              console.log(city.id, historyArr);
              j--;
              // 去重问题
            }
          }
        } */

        // 使用map去重
        let map = new Map();
        for (let item of historyArr) {
          if (!map.has(item.id)) {
            map.set(item.id, item);
          }
        }
        // console.log("map", map);
        // 重新解构后赋值给historyArr
        historyArr = [...map.values()];

        // 把历史记录数组传到历史列表
        if (historyArr) {
          this.historyList = historyArr;
          // console.log(this.historyList);
        }
        // 上传历史记录
        localStorage.setItem("history", JSON.stringify(historyArr));
      } else {
        // 如果没有传入城市就直接渲染历史记录
        let historys = localStorage.getItem("history");
        let historyArr = [];
        if (historys) {
          historyArr = JSON.parse(historys);
        }
        historyArr = _.uniq(historyArr);
        if (historyArr) {
          this.historyList = historyArr;
          // console.log(this.historyList);
        }
      }
    },
    // 清空历史
    delhistory() {
      localStorage.setItem("history", "");
      this.setHistroy();
    },
    // 定位
    getMyPosition() {
      if (window.navigator.geolocation) {
        // console.log("正在获取您的位置。");
      } else {
        // alert("当前浏览器不支持");
      }
    },
  },
  created() {
    // 城市列表 最受好评电影列表
    this.axios.get("cities.json").then((re) => {
      // console.log(re);
      this.reHot = re.hot;
      // this.hotList = re.hot;
      this.cities = re.cts;
      // [{ str: "A", arr: [] }];

      var cts = re.cts;
      var catys = [];

      cts.forEach((item) => {
        var str = item.py.substring(0, 1).toUpperCase();
        var catArr = false;
        var catindex = null;

        for (let i = 0; i < this.reHot.length - 1; i++) {
          if (item.nm == this.reHot[i]) {
            // console.log("这个是hot", item);
            this.hotList.push(item);
          }
        }

        // console.log(item);
        catys.forEach((city, index) => {
          if (city.str == str) {
            catArr = true;
            catindex = index;
          }
        });
        if (catArr) {
          catys[catindex].arr.push(item);
        } else {
          catys.push({
            str: str,
            arr: [item],
          });
        }
        // console.log("catys", catys);
      });

      catys.arr = _.orderBy(
        catys.arr,
        ["id", "nm", "py"],
        ["asc", "asc", "asc"]
      );

      this.cities = _.orderBy(catys, ["str", "arr"], ["asc", "asc"]);
      // 城市列表 最受好评电影列表结尾
      this.cities.forEach((item) => {
        // console.log(item.str);
        this.indexList.push(item.str);
      });
      // console.log(this.cities);

      /*   this.cities.forEach((item) => {
        // console.log(item);  // 城市分类
      }); */
    });
    // console.log(this.cities);  这里拿不到
    this.setHistroy();
  },

  computed: {},
};
</script>

<style lang="scss" scoped>
.CityLocation {
  position: fixed;
  z-index: 999;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #ebebeb;
  font-size: 14px;

  overflow-y: scroll;
  button {
    border: none;
    background: none;
    border: 0.02rem solid #e6e6e6;
  }
  // 定位
  .location-city {
    background: #f5f5f5;
    padding-top: 15px;
    button {
      background-color: #fff;
      width: auto;
      padding: 0 20px;
      line-height: 30px;
    }
  }

  // 清空最近
  .delhistory {
    // width: 80px;
    padding: 3px 5px;
    margin-left: 10px;
    background-color: #e54847;
    border-radius: 10px;
    line-height: 30px;

    color: #fff;
    font-size: 12px;
  }
  // 最近
  .recently-city {
    min-height: 10px;
    background-color: #f5f5f5;

    .recently {
      display: flex;
      justify-content: left;
      flex-wrap: wrap;

      li {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background-color: #fff;
        text-align: center;
        border-radius: 4px;
        margin: 5px 13px 0 0;
      }
    }
  }

  // 热门
  .hot-city {
    background-color: #f5f5f5;
    .list {
      display: flex;
      justify-content: left;
      flex-wrap: wrap;

      li {
        width: 100px;
        height: 33px;
        line-height: 33px;
        background-color: #fff;
        text-align: center;
        border-radius: 5px;
        margin: 5px 13px 10px 0;
      }
    }
  }

  .A-Z {
    background-color: #f5f5f5;
    .city-list {
      height: 45px;
      margin-left: 15px;
      background-color: #f5f5f5;

      color: #333;
      font-size: 14px;
      line-height: 45px;
      border-bottom: 0.02rem solid #c8c7cc;
    }
  }
}
</style>


<style lang="scss" >
.van-index-bar__index {
  padding: 0 5px 0 16px;
  font-weight: 500;
  font-size: 10px;
  line-height: 17px;
}
.van-index-anchor {
  background-color: #ebebeb !important;
}
.van-index-bar__index {
  height: 20px;
}
</style>